import { type Component, type JSXElement, Show } from "solid-js";
import { Dynamic } from "solid-js/web";
import './index.module.css'

export type SlotTemplate = JSXElement | Component<any>;

export type NamedSlotTemplates = {
  [key: string]: SlotTemplate;
};

export interface Slots<T extends NamedSlotTemplates> {
  slots?: T;
}

export interface SlotProps<S extends SlotTemplate> {
  slot?: S;
  context?: S extends (props: infer P) => JSXElement ? P : {};
  children?: (
    props: S extends (props: infer P) => JSXElement ? P : {}
  ) => JSXElement;
}

export const Slot = <S extends SlotTemplate>(props: SlotProps<S>) => {
  const slotTemplate = props.slot ?? props.children;

  const component =
    typeof slotTemplate === "function" ? slotTemplate : () => slotTemplate;

  return (
    <Show when={component}>
      <Dynamic component={component} {...(props.context as any)}></Dynamic>
    </Show>
  );
};

export default Slot
